import {
    getProjectList,getTeamsByProjectId,verifyCodeFun
  } from './talkDailyReportServ'
  // import { parse } from 'qs'
  import $ from 'jquery'
  import { message } from 'antd'
  import moment from 'moment'
  import axios from 'axios'
  import {isEmpty, isArray, cloneDeep, merge} from 'lodash'
  import { makeAddress ,download} from "utils/util"
  import config from 'config/config'
  
  const defultState = {
      id:"",
      biz:{
        queryForm:{
          startTime:moment().startOf('month').format('YYYY-MM-DD'),
          endTime:moment().endOf('month').format('YYYY-MM-DD'),
        }
      },
      areaList: [],
      products: [],
      teamList: [],
  }
  
  const tmpModule = {
    state: cloneDeep(defultState),
    subscriptions: {
      setup ({dispatch, history}) {
        history.listen(({ pathname, query }) => {
          if('' + tmpModule.pathname === '' + pathname){
            dispatch({type: 'updateStore', payload: cloneDeep(defultState)})
            dispatch({type: 'getProjectList', payload: {}})
          }
        })
      },
    },
  
  
    effects: {
      *down({payload}, {put, call, select}) {
          let {biz} = yield select(state => state[tmpModule.namespace])
          
          let params = {...biz.queryForm}
          if(biz.queryForm.areaId&&biz.queryForm.areaId.length){
            params['areaId'] = biz.queryForm.areaId.join(',')
          }
          if(biz.queryForm.projectId&&biz.queryForm.projectId.length){
            params['projectId'] = biz.queryForm.projectId.join(',')
          }
          if(biz.queryForm.teamId&&biz.queryForm.teamId.length){
            params['teamId'] = biz.queryForm.teamId.join(',')
          }
          params['type'] = 4
        axios({
            method: 'post',
            url: config.baseUrl+`zituo-admin/a/report/excelStyleData`,
            responseType: 'blob',
            headers: {},
            data: params,
        }).then(res => {
            const content = res.data
            console.log(res)
            const blob = new Blob([content])
            Date.prototype.Format = function (fmt) { // author: meizz
                var o = {
                    "M+": this.getMonth() + 1, // 月份
                    "d+": this.getDate(), // 日
                    "h+": this.getHours(), // 小时
                    "m+": this.getMinutes(), // 分
                    "s+": this.getSeconds(), // 秒
                    "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
                    "S": this.getMilliseconds() // 毫秒
                };
                if (/(y+)/.test(fmt))
                    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
                for (var k in o)
                    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                        return fmt;
            }
            let dateTime = new Date().Format("yyyy-MM-dd hh:mm:ss");
            let fileName = `拓客日报 ${dateTime}.xls`
            if ('download' in document.createElement('a')) { // 非IE下载
              const elink = document.createElement('a')
              elink.download = fileName
              elink.style.display = 'none'
              elink.href = URL.createObjectURL(blob)
              document.body.appendChild(elink)
              elink.click()
              URL.revokeObjectURL(elink.href) // 释放URL 对象
              document.body.removeChild(elink)
            } else { // IE10+下载
              navigator.msSaveBlob(blob, fileName)
            }
            message.success('导出成功')
        })
      },
      //获取区域项目
      *getProjectList({payload},{put,select,call}){
        let {areaList} = yield select(state => state[tmpModule.namespace])
        let params = {
            level : 2 
          }
        if(yield call(verifyCodeFun,{})){
         const { data } = yield call(getProjectList, {...params})
          let list = data
          if(!list.length){
            return
          }
          areaList =  list.map((item,index)=>{
            return {
              label: item.buname,
              value: item.buguid,
              children: item.childSysUninessunitList
            }
          })
          yield put({type: 'updateStore', payload: {areaList}})
          yield put({type: 'filterProjectList', payload: {}})
        }
      },
      *getTeamsByProjectId({payload},{put,select,call}){
          let {teamList} = yield select(state => state[tmpModule.namespace])
          let params = {
            projectId:payload.id,
            }
          const { success,rows } = yield call(getTeamsByProjectId, {...params})
          if(success){
            teamList = rows
            if(!rows.length){
              return
            }
            teamList =  rows.map((item,index)=>{
              return {
                label: item.team_name,
                value: item.id,
              }
            })
            yield put({type: 'updateStore', payload: {teamList}})
          }
      },
      *filterProjectList({payload},{put,select,call}){    
        let {products,areaList,biz} = yield select(state => state[tmpModule.namespace])
        let list = []
        if(biz.queryForm.areaId&&biz.queryForm.areaId.length){
          for(var item of areaList){
            for(var itemed of biz.queryForm.areaId){
              if(itemed&&item.value == itemed){
                list.push(...item.children)
              }
            }
          }
        }
        if(list.length){
          products =  list.map((item,index)=>{
            return {
              label: item.buname,
              value: item.buguid,
            }
          })
        }
        yield put({type: 'updateStore', payload: {products}})
      },
    },
    // 存入状态机
    reducers: {
      updateStore(preState, action) {
        return Object.assign({}, preState, action.payload)
      },
    }
  }
  
  export default tmpModule
  